#!/usr/bin/env python3
# Author: Joshua Chen
# Date: 2015-12-25
# Location: Shenzhen
# Desc: manage public keys for shadow git

import os, sys
prog_path = os.path.realpath(__file__)
prog_dir  = os.path.dirname(prog_path)
sys.path.insert(0, prog_dir)
import lib

class KeyManager:
    """ Add, remove, list public keys of the shadow git
    """
    def __init__(self, argv):
        argv = argv[1:]
        cmd  = argv.pop(0)
        if cmd == "add":
            if len(argv) == 3:
                self.add(*argv)
            else:
                self.add()
        elif cmd == "remove":
            self.remove(argv[0])
        elif cmd == "list":
            self.list()
        else:
            raise lib.WrongArgumentException

    def list(self):
        lib.list_pubkeys()

    def add(self, name=None, email=None, keyid=None):
        lib.add_pubkey(name, email, keyid)

    def remove(self, keyword):
        if not lib.remove_pubkey(keyword):
            raise Exception


def help(ofile=sys.stdout):
    """ Show help message
    """
    msg =  'Usage: %s list\n' % os.path.basename(sys.argv[0])
    msg += '       %s add [name] [email] [keyid]\n' % os.path.basename(sys.argv[0])
    msg += '       %s remove [name|email|keyid]' % os.path.basename(sys.argv[0])
    print(msg, file=ofile)


if __name__ == '__main__':
    if not lib.env_ok():
        exit(1)
    try:
        KeyManager(sys.argv)
    except (IndexError, lib.WrongArgumentException) as e:
        help(sys.stderr)
        exit(1)
    except KeyboardInterrupt:
        exit(1)
    except:
        exit(1)
    else:
        exit(0)
